package com.pz.cloud.framework.workflow.listener;

import com.pz.cloud.framework.base.threadLocal.ThreadLocalContext;
import com.pz.cloud.framework.business.workflow.entity.ProcessInfo;
import com.pz.cloud.framework.business.workflow.entity.TaskNodeAttr;
import com.pz.cloud.framework.business.workflow.entity.WaitDone;
import com.pz.cloud.framework.business.workflow.entity.WaitDoneUser;
import com.pz.cloud.framework.business.workflow.enums.WorkflowEnum;
import com.pz.cloud.framework.business.workflow.service.IProcessInfoService;
import com.pz.cloud.framework.business.workflow.service.ITaskNodeAttrService;
import com.pz.cloud.framework.business.workflow.service.IWaitDoneService;
import com.pz.cloud.framework.workflow.mapper.WaitDoneUserMapper;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.impl.ProcessEngineImpl;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.UUIDUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * 任务创建事件监听器
 * @author mzz
 */
public class TaskCreateListener implements ActivitiEventListener {
    private final static Logger LOG = LoggerFactory.getLogger(TaskCreateListener.class);


    @Override
    public void onEvent(ActivitiEvent event) {
        WaitDoneUserMapper waitDoneUserMapper = SpringContextUtils.getBean(WaitDoneUserMapper.class);
        IWaitDoneService waitDoneService = SpringContextUtils.getBean(IWaitDoneService.class);
        ISysUserService sysUserService = SpringContextUtils.getBean(ISysUserService.class);

        ProcessEngineImpl processEngine = SpringContextUtils.getBean(ProcessEngineImpl.class);
        ITaskNodeAttrService taskNodeAttrService = SpringContextUtils.getBean(ITaskNodeAttrService.class);

        ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event;
        TaskEntity task = (TaskEntity) entityEvent.getEntity();
        IProcessInfoService processInfoService =  SpringContextUtils.getBean(IProcessInfoService.class);
        String processInstanceId = task.getProcessInstanceId();

        ProcessInfo processInfo = processInfoService.getById(processInstanceId);
        String bizId = null;
        if(processInfo==null){//任务开启时
            processInfo = ThreadLocalContext.processInfoThreadLocal.get();
        }
        if(processInfo!=null){
            bizId = processInfo.getRelatedId();
        }
        /*
         * 1.创建待办的主表数据，用于存储当前流程相关信息
         * 2.创建子表信息，用于存储每一个处理人的信息
         */
        String parentId = null; //上一步任务id
        Object preTask = ThreadLocalContext.PreTaskThreadLocal.get();
        if(preTask!=null&&preTask instanceof Task){
            parentId = ((Task) preTask).getId();
        }
        WaitDone waitDone = new WaitDone();
        // 手动创建主键,为了保证waitDonePk和waitPk保持一致
        // 1.主表数据
        waitDone.setId(task.getId());
        waitDone.setProcessInstanceId(processInstanceId);
        waitDone.setTaskName(task.getName());
        waitDone.setSource(WorkflowEnum.WaitDoneSource.activiti.name());
        waitDone.setBizId(bizId);
        waitDone.setStatus(WorkflowEnum.WaitDoneStatus.未完成.getStatus());
        waitDone.setDelFlag(0);
        waitDone.setParentId(parentId);
        waitDone.setTaskKey(task.getTaskDefinitionKey());

        TaskNodeAttr taskNodeAttr = taskNodeAttrService.getById(task.getTaskDefinitionKey());
        if(taskNodeAttr!=null&&taskNodeAttr.getPeriod()!=null){
            task.setDueDate(DateUtils.addDays(new Date(),taskNodeAttr.getPeriod()));
            waitDone.setDueDate(task.getDueDate());
        }

        waitDoneService.save(waitDone);

        List<IdentityLink> identityLinks = processEngine.getTaskService().getIdentityLinksForTask(task.getId());
        if(CollectionUtils.isNotEmpty(identityLinks)){
            for (IdentityLink identityLink : identityLinks) {
                WaitDoneUser waitDoneUser = new WaitDoneUser();
                waitDoneUser.setId(UUIDUtils.uuid32());
                waitDoneUser.setWaitDoneId(task.getId());
                waitDoneUser.setWaitUserId(identityLink.getUserId());
                SysUser sysUser = sysUserService.getById(identityLink.getUserId());
                if(sysUser!=null){
                    waitDoneUser.setWaitUserName(sysUser.getRealname());
                }
                waitDoneUserMapper.insert(waitDoneUser);

            }

        }
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }
}
